package cn.lblbc.appstore.utils

import android.content.Context
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.os.Environment
import android.util.Log
import cn.lblbc.appstore.module.download.DownloadFileInfo
import cn.lblbc.appstore.module.download.DownloadStatus
import cn.lblbc.appstore.module.download.StatusManager
import cn.lblbc.appstore.utils.AppUtils.install
import cn.lblbc.lib.download.FileDownloadListener
import cn.lblbc.lib.download.FileDownloadManager

object DownloadUtils {
    private val tag = "DownloadUtils"
    fun downloadAndInstall(context: Context, packageName: String, apkUrl: String): String {
        val downloadDir = Environment.getExternalStorageDirectory().path + "/Download"
        val downloadTask = FileDownloadManager.createDownloadTask(apkUrl, downloadDir)
        val downloadTaskId = FileDownloadManager.download(downloadTask, object : FileDownloadListener {
            override fun onDownloadProgressChange(fileSize: Long, downloadedSize: Long, speed: Int) {
                StatusManager.notifyDownloadChanges(packageName, DownloadFileInfo(DownloadStatus.STATUS_DOWNLOADING, fileSize, downloadedSize))
                if (downloadedSize == fileSize) {
                    install(context, packageName, downloadTask.getFilePath())
                }
            }

            override fun onError(errorCode: Int, httpErrorCode: Int, msg: String) {
                StatusManager.notifyDownloadChanges(packageName, DownloadFileInfo(DownloadStatus.STATUS_PAUSE, 0, 0))
            }
        })
        return downloadTaskId
    }

    fun pauseDownload(taskId: String) {
        FileDownloadManager.pauseDownload(taskId)
    }
}